from urllib.parse import urlencode
from bodhi.wsgi import HttpError

class AuthFilter:
    '''It's required that any views applied with AuthFilter 
    have "user" property set.
    '''
    order = 100

    def __init__(self, *roles):
        self.roles = roles

    def __call__(self, view, next):
        user = getattr(view, 'user', None)
        if not user:
            request = view.request
            if request.method == "GET" and not request.is_ajax:
                url = view.settings.LOGIN_URL + "?" + urlencode({'next': request.uri})
                view.redirect_to_uri(url)
                return
            raise HttpError(401)
        elif self.roles and user.role not in self.roles:
            raise HttpError(403)
        next()
        view.response.set_header('Cache-Control', 'private')
        view.response.set_header('Vary', 'cookie')

